const co = require('co');
const async = require('async');
const eos = require('./eos');
const logger = require('../utils/logger');

const { insertLog } = require(__base + '/lib/serviceLogger');

const CONCURRENCY = 1;

let accountCreationTask = co.wrap(function *(acReq, cb) {
    logger.info(acReq.accountName);

    try {
        let accountQuota = eos.getNewAccountQuota();

        yield eos.createAccount({
            accountName: acReq.accountName,
            publicKey: acReq.publicKey,
            ram: accountQuota.ram,
            netStake: accountQuota.netStake,
            cpuStake: accountQuota.cpuStake
        });

        acReq.status = 'complete',
        yield acReq.save();
    } catch (e) {
        logger.error(e.toString());
        acReq.status = 'failToCreate',
        yield acReq.save();
        insertLog('error', `${acReq.accountName} ${e.toString()}`)
    }

    cb();
});

var accountCreationQueue = async.queue(accountCreationTask, CONCURRENCY);

module.exports.add = function (acReq) {
    return new Promise((resolve, reject) => {
        accountCreationQueue.push(acReq, err => {
            logger.info(`${accountCreationQueue.length()} account creation requests in queue.`);
            if (err) reject(err);
            else resolve();
        });
        logger.info(`${accountCreationQueue.length()} account creation requests in queue.`);
    });
};
